package com.atomscat.lottery.config.db;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

@Slf4j
@Configuration
public class DatabaseCreator {
    /**
     * The name of the database.
     */
    @Value("${spring.application.name}")
    private String databaseName;
    /**
     * The URL of the database.
     */
    @Value("${spring.datasource.url}")
    private String databaseUrl;
    /**
     * The username for the database.
     */
    @Value("${spring.datasource.username}")
    private String databaseUsername;
    /**
     * The password for the database.
     */
    @Value("${spring.datasource.password}")
    private String databasePassword;

    @Value("${spring.sql.init.platform}")
    private String platform;

    /**
     * The constructor for DatabaseCreator.
     *
     * @throws Exception
     */
    @PostConstruct
    public void run() throws Exception {
        switch (platform) {
            case "postgresql": {
                createPostgresDatabase();
                break;
            }
            case "mysql": {
                // MySQL database creation logic can be added here
                log.info("MySQL database creation logic is not implemented yet.");
                break;
            }
            case "oracle": {
                // Oracle database creation logic can be added here
                log.info("Oracle database creation logic is not implemented yet.");
                break;
            }
            case "sqlserver": {
                // SQL Server database creation logic can be added here
                log.info("SQL Server database creation logic is not implemented yet.");
                break;
            }
            default: {
                log.error("Unsupported database platform: {}", platform);
                break;
            }
        }
    }

    /**
     * Creates a PostgresSQL database.
     *
     * @throws Exception if an error occurs
     */
    private void createPostgresDatabase() throws Exception {
        try (Connection conn = DriverManager.getConnection(databaseUrl, databaseUsername, databasePassword);
             Statement stmt = conn.createStatement()) {
            ResultSet rs = stmt.executeQuery("SELECT 1 FROM pg_database WHERE datname = '" + databaseName + "'");
            if (!rs.next()) {
                stmt.executeUpdate("CREATE DATABASE " + databaseName + " WITH ENCODING 'UTF8' TEMPLATE template0");
                log.info("Database '{}' created.", databaseName);
            } else {
                log.info("Database '{}' already exists.", databaseName);
            }
        }
    }

    /**
     * Creates a DataSource bean for the main database.
     *
     * @return the DataSource
     */
    @Bean
    @Primary
    public DataSource mainDataSource() {
        return DataSourceBuilder.create()
                .url("jdbc:postgresql://localhost:5432/" + databaseName)
                .username(databaseUsername)
                .password(databasePassword)
                .driverClassName("org.postgresql.Driver")
                .build();
    }
}
